package xyz.zhouzhaodong.crm.interceptor;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import xyz.zhouzhaodong.crm.util.TokenUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 *
 * @author zhouzhaodong
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 请求类型
        String options = "OPTIONS";
        if (options.equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        response.setCharacterEncoding("utf-8");

        // token放在header中的名称
        String headerTokenName = "CRMTOKEN";
        String token = request.getHeader(headerTokenName);
        if (token != null) {
            boolean result = TokenUtil.verify(token);
            if (result) {
                logger.info("认证成功，通过拦截器");
                return true;
            }
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            // 认证失败返回错误信息
            JSONObject json = new JSONObject();
            json.put("code", -1);
            json.put("message", "认证失败，未通过拦截器");
            json.put("data", "");
            response.getWriter().append(json.toString());
            logger.info("认证失败，未通过拦截器");
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(500);
            return false;
        }
        return false;
    }

}
